package com.shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shop.mapper.GoodsMapper;
import com.shop.mapper.OrderItemMapper;
import com.shop.mapper.ShopcartMapper;
import com.shop.pojo.Goods;
import com.shop.pojo.OrderItem;
import com.shop.pojo.Shopcart;
import com.shop.service.OrderItemService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class OrderItemServiceImpl implements OrderItemService {
    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private ShopcartMapper shopcartMapper;

    @Override
    public List<OrderItem> findAll(Integer id) {
        QueryWrapper<OrderItem> wrapper = new QueryWrapper<>();
        wrapper.eq("orders_id",id);
        List<OrderItem> list = orderItemMapper.selectList(wrapper);
        for (int i = 0;i<list.size();i++){
            OrderItem orderItem = list.get(i);
            int gid = orderItem.getGoodsId();
            Goods goods = goodsMapper.selectById(gid);
            orderItem.setGoodsName(goods.getName());
            orderItem.setGoodsPrice(goods.getPrice());
            list.set(i,orderItem);
        }
        return list;
    }

    @Override
    public void add(Integer gid, Integer oid, Integer uid, Integer number) {
        OrderItem orderItem = new OrderItem();
        orderItem.setGoodsId(gid);
        orderItem.setOrdersId(oid);
        orderItem.setUserId(uid);
        orderItem.setNumber(number);
        orderItemMapper.insert(orderItem);
        QueryWrapper<Shopcart> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id",gid).eq("user_id",uid);
        shopcartMapper.delete(wrapper);
        QueryWrapper<Goods> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("goods_id",gid);
        Goods goods = goodsMapper.selectOne(wrapper1);
        goods.setNumber(goods.getNumber()+1);
        goodsMapper.updateById(goods);
    }
}
